<?php
declare (strict_types=1);

namespace ciphertext;

/**
 * Iot数据帧RSA加解密
 */
class RsaIotData
{

    //公钥
    public static string $publicKey = '-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsuTbYSmh7bxGqexoR0Kz
lpGkK9LefjODxn6MhuOMFPxtp6c7KtgNbnxOL4SpLOUZYUutGgPzXABFxD64/DRU
VkeikEyR6OJa/j607IstmXKMulkQvxzY5gFk79Xi/fMS1AMEA7t72RmvG3f/032w
SilWRzbuhweyVZ3BI0e4Q1AAb3QeWC2pKJqbhWRbL7xj96vlkWfGh2Z7u46gI6a+
KnrfgX1cH0PvzWLtCiIQDi98M4dKfEILQfRsuitVYAJMz+IS57G88uIKU2H2Q8Te
sW0Y46w2zvsa/pdfvBdDoa5raJHXUvMUBCDswuPvtNtYatznx2v4bXmtO8o6jLF+
5wIDAQAB
-----END PUBLIC KEY-----';

    //私钥
    private static string $privateKey = '-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCy5NthKaHtvEap
7GhHQrOWkaQr0t5+M4PGfoyG44wU/G2npzsq2A1ufE4vhKks5RlhS60aA/NcAEXE
Prj8NFRWR6KQTJHo4lr+PrTsiy2Zcoy6WRC/HNjmAWTv1eL98xLUAwQDu3vZGa8b
d//TfbBKKVZHNu6HB7JVncEjR7hDUABvdB5YLakompuFZFsvvGP3q+WRZ8aHZnu7
jqAjpr4qet+BfVwfQ+/NYu0KIhAOL3wzh0p8QgtB9Gy6K1VgAkzP4hLnsbzy4gpT
YfZDxN6xbRjjrDbO+xr+l1+8F0OhrmtokddS8xQEIOzC4++021hq3OfHa/htea07
yjqMsX7nAgMBAAECggEBAKkcYSpTkejL/7zoZ5ddvalLmnd3Cq8ggaSlwrBM8QJx
sjM3il4xCVl1lu+ip85x8HEiecvLCkXhWBJw/Kwlx8gcRdfFGnWdbUlE/AFUfFG/
kLskMQmI+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W0Ch+O7hqVRX1sH1
K/fqEbXtt1rDKWJpYrLOmSOi
-----END PRIVATE KEY-----';

    /**
     * 使用公钥加密
     * @param string $data
     * @return false|string
     */
    public static function publicEncrypt(string $data): bool|string
    {
        //公钥加密
        //第一个参数是待加密的数据只能是string，第二个参数是加密后的数据
        $return_en = openssl_public_encrypt($data, $crypted, self::$publicKey);
        if (!$return_en) {
            return false;
        }
        return base64_encode($crypted);
    }

    /**
     * 使用公钥解密
     * @param string $data
     * @return false|mixed
     */
    public static function publicDecrypt(string $data): mixed
    {
        $return_de = openssl_public_decrypt(base64_decode($data), $decrypted, self::$publicKey);
        if (!$return_de) {
            return false;
        }
        return $decrypted;
    }

    /**
     * 使用私钥加密
     * @param string $data
     * @return false|string
     */
    public static function privateEncrypt(string $data): bool|string
    {
        //公钥加密
        //第一个参数是待加密的数据只能是string，第二个参数是加密后的数据
        $return_en = openssl_private_encrypt($data, $crypted, self::$privateKey);
        if (!$return_en) {
            return false;
        }
        return base64_encode($crypted);
    }

    /**
     * 使用私钥解密
     * @param string $data
     * @return mixed
     */
    public static function privateDecrypt(string $data): mixed
    {
        $return_de = openssl_private_decrypt(base64_decode($data), $decrypted, self::$privateKey);
        if (!$return_de) {
            return false;
        }
        return $decrypted;
    }


}
